import React, { useState, useEffect } from 'react';
import { useLocation, history } from 'umi';
import { Form, Row, Button, Space } from 'antd';
import moment from 'moment';
import PageRender from '@/components/PageRender';
import FormItemRender from './components/FormItemRender';
import {
  create,
  queryDetails,
  queryParticipantsList,
  queryHoseNameList,
  editHoseNameList,
} from '@/pages/DarkPleaseCloseYourEyes/services';
import {
  formItemLayout,
  config,
} from '@/pages/DarkPleaseCloseYourEyes/constant';
import './style.less';
// 身份
const identityMap: any = {
  killerList: '杀',
  policeList: '警',
  civilianList: '民',
};
// 身份状态
const ID_StatusMap: any = {
  killNum: '被杀',
  throw: '被投',
};

const list = [
  {
    label: '游戏',
  },
  {
    label: '天黑请闭眼',
    href: '/game/dark-please-close-your-eyes',
  },
  {
    label: '新建游戏',
  },
];

export default (props: any) => {
  const [form] = Form.useForm();
  const location: any = useLocation();
  const type = location.query.type;
  const id = location.query.id;
  const [breadcrumb, setBreadcrumb] = useState(list);
  const [title, setTitle] = useState('新建游戏');
  // 参与人员
  const [participantsList, setParticipantsList] = useState([]);
  // 座位数据
  const [seatingData, setSeatingData] = useState<any>([]);

  // 初始化调用
  const init = () => {
    // 新建
    if (type === 'add') {
      const PAlist =
        queryParticipantsList()?.map((item: any) => item.label) || [];
      // 读取参与人员
      setParticipantsList(queryParticipantsList());
      // 默认值
      form.setFieldsValue({
        gameName: '天黑黑',
        modeType: '天黑请闭眼',
        hostName: queryHoseNameList() || [],
        startTime: moment(new Date()),
        participantsList: PAlist,
      });
    } else {
      // 详情
      const data = queryDetails(id);
      // 读取参与人员
      setParticipantsList(
        data.participantsList.map((item: any, i: number) => ({
          key: i + 1,
          label: item,
        })),
      );
      setBreadcrumb([
        {
          label: '游戏',
        },
        {
          label: '天黑请闭眼',
          href: '/game/dark-please-close-your-eyes',
        },
        {
          label: data.gameName,
        },
      ]);
      setTitle(data.gameName);
      const formData = {
        ...data,
        startTime: moment(data.startTime),
      };
      console.log(formData, queryParticipantsList());
      form.setFieldsValue(formData);
    }
  };

  // 跳转到列表页
  const back = () => {
    history.push({
      pathname: '/game/dark-please-close-your-eyes',
    });
  };

  // 保存
  const onSave = () => {
    form.validateFields().then((formData) => {
      const params = {
        ...formData,
        startTime: formData.startTime.format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        duration: Math.ceil((+new Date() - formData.startTime) / 60000),
      };
      console.log(params);
      create(params);
      editHoseNameList(formData.hostName);
      back();
    });
  };

  const dayListChange = (allValues: any) => {
    const dayListvalue = allValues.dayList || [];
    const ID_StatusList: any = [];
    const identityList: any = [];

    dayListvalue.forEach((item: any) => {
      Object.keys(ID_StatusMap).forEach((idKey) => {
        if (item?.[idKey]) {
          ID_StatusList.push({
            num: item?.[idKey],
            ID_Status: ID_StatusMap[idKey],
          });
        }
      });
    });

    Object.keys(identityMap).forEach((idKey) => {
      if (allValues?.[idKey]) {
        allValues?.[idKey].forEach((item: any) => {
          identityList.push({
            num: item,
            identity: identityMap[idKey],
          });
        });
      }
    });
    const list: any = participantsList.map((item: any, i: number) => {
      const ID_Status = ID_StatusList.find((idKey: any) => idKey.num === i + 1);
      const identity = identityList.find((idKey: any) => idKey.num === i + 1);

      return {
        ...item,
        ID_Status: ID_Status?.ID_Status,
        identity: identity?.identity,
      };
    });

    setSeatingData(list);
  };
  const onValuesChange = (changeValue: any, allValues: any) => {
    dayListChange(allValues);
  };

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    dayListChange(form.getFieldsValue(true));
  }, [participantsList]);

  return (
    <PageRender list={breadcrumb} title={title} className="THH-Form">
      {seatingData.length > 0 && (
        <div className="seating-table">
          <div className="left">
            {seatingData
              .slice(0, Math.ceil(seatingData.length / 2))
              .reverse()
              .map((item: any) => (
                <div key={item.key} className="avatar">
                  {item.ID_Status}
                  <div className="num">{item.key}</div>
                  <div className="identity">{item.identity}</div>
                </div>
              ))}
          </div>
          <div className="right">
            {seatingData
              .slice(Math.ceil(seatingData.length / 2))
              .map((item: any) => (
                <div key={item.key} className="avatar">
                  {item.ID_Status}
                  <div className="num">{item.key}</div>
                  <div className="identity">{item.identity}</div>
                </div>
              ))}
          </div>
          <div className="bottom">主持人</div>
        </div>
      )}
      <div className="section">
        <Form onValuesChange={onValuesChange} form={form} {...formItemLayout}>
          <Row>
            <FormItemRender
              config={config}
              form={form}
              participantsList={participantsList}
              setParticipantsList={setParticipantsList}
              dayListChange={dayListChange}
            ></FormItemRender>
          </Row>
        </Form>
      </div>
      <footer>
        <Row className="action-box" justify="center">
          <Space size={8}>
            <Button type="primary" onClick={onSave}>
              保存
            </Button>
            <Button onClick={back}>返回</Button>
          </Space>
        </Row>
      </footer>
    </PageRender>
  );
};
